package com.yitao.cms.service.order;

import com.querydsl.core.types.Order;
import com.querydsl.core.types.OrderSpecifier;
import com.skipper.base.bean.CommonStatus;
import com.skipper.base.bean.DataOutput;
import com.skipper.base.bean.PagedInput;
import com.skipper.base.bean.PagedOutput;
import com.skipper.base.data.querydsl.PredicateBuilder;
import com.skipper.base.service.GenericEntityService;
import com.yitao.client.dto.expressage.ServicesCompanyInfoDto;
import com.yitao.client.model.expressage.QServicesCompanyInfoModel;
import com.yitao.client.model.expressage.ServicesCompanyInfoModel;
import com.yitao.cms.constant.UserSession;
import com.yitao.cms.service.expressage.ExpressageMatchingDetailCmsService;
import com.yitao.cms.utils.BaseUtils;
import com.yitao.cms.utils.DateUtils;
import com.yitao.cms.vo.expressage.ServicesCompanyInfoVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CmsServicesCompanyInfoService extends GenericEntityService<ServicesCompanyInfoModel, ServicesCompanyInfoDto, QServicesCompanyInfoModel> {
    private BaseUtils baseUtils = BaseUtils.getInstance();
    @Autowired
    private ExpressageMatchingDetailCmsService expressageMatchingDetailCmsService;

    public CmsServicesCompanyInfoService(EntityManager entityManager) {
        super(entityManager);
    }


    public List<ServicesCompanyInfoModel> getServicesCompanyInfoModelList() {
        return queryFactory.select(Q).from(Q).where(Q.isDelete.eq(false)).orderBy(Q.idx.asc()).fetch();
    }


    public ServicesCompanyInfoModel getServicesCompanyInfoModelById(Long id) {
        return queryFactory.select(Q).from(Q).where(Q.id.eq(id)).fetchOne();
    }

    /**
     *
     * 功能描述: 根据快递公司编号获取快递公司信息
     *
     * @param companyCode 快递公司编码
     * @return
     * @auther: Kien
     * @date: 2019/6/12 10:34
     */
    public ServicesCompanyInfoModel getServicesCompanyInfoByNameabbr(String companyCode) {
        if(StringUtils.isBlank(companyCode)) {
            return null;
        }
        List<ServicesCompanyInfoModel> all = repository.findAll(PredicateBuilder.conjunction().and(() -> Q.nameAbbr.eq(companyCode)).and(() -> Q.isDelete.eq(false)).get());
        if(CollectionUtils.isEmpty(all)) {
            return null;
        }
        return all.get(0);
    }

    /**
     *
     * 功能描述: 新增
     *
     * @param companyName 物流公司名称
     * @param nameAbbr 物流公司编码
     * @param logoUrl 物流公司logo
     * @param idx 排序值
     * @param userId 用户id
     * @return
     * @auther: Kien
     * @date: 2019/6/12 18:17
     */
    @Transactional
    public ServicesCompanyInfoModel save(String companyName, String nameAbbr, String logoUrl, Integer idx, Long userId) {
        List<ServicesCompanyInfoModel> all = repository.findAll(PredicateBuilder.conjunction()
                .and(() -> Q.isDelete.eq(false))
                .and(() -> Q.nameAbbr.eq(nameAbbr))
                .get(), new OrderSpecifier<>(Order.DESC, Q.lastUpdateTime));
        if(CollectionUtils.isEmpty(all)) {
            ServicesCompanyInfoModel servicesCompanyInfoModel = new ServicesCompanyInfoModel();
            servicesCompanyInfoModel.setIsDelete(false);
            servicesCompanyInfoModel.setCompanyName(companyName);
            servicesCompanyInfoModel.setIdx(idx);
            servicesCompanyInfoModel.setLogoUrl(logoUrl);
            servicesCompanyInfoModel.setNameAbbr(nameAbbr);
            servicesCompanyInfoModel.setCreateBy(userId);
            servicesCompanyInfoModel.setLastUpdateBy(userId);
            servicesCompanyInfoModel.setCreateTime(new Date());
            servicesCompanyInfoModel.setLastUpdateTime(new Date());
            return repository.save(servicesCompanyInfoModel);
        } else {
            // 如果存在，执行修改操作
            ServicesCompanyInfoModel servicesCompanyInfoModel = all.get(0);
            repository.updateByWhere(PredicateBuilder.conjunction().and(() -> Q.id.eq(servicesCompanyInfoModel.getId())).get(), it -> {
                it.set(Q.companyName, companyName == null ? servicesCompanyInfoModel.getCompanyName() : companyName);
                it.set(Q.logoUrl, logoUrl == null ? servicesCompanyInfoModel.getLogoUrl(): logoUrl);
                it.set(Q.idx, idx == null ? servicesCompanyInfoModel.getIdx() : idx);
                it.set(Q.lastUpdateBy, userId);
            });
            return servicesCompanyInfoModel;
        }




    }

    /**
     *
     * 功能描述: 获取物流商列表
     * @param companyName 物流商名称
     * @param pageNo 当前页码
     * @param pageSize 每页显示条数
     *
     * @return
     * @auther: Kien
     * @date: 2019/6/12 19:22
     */
    public PagedOutput<ServicesCompanyInfoVo> getServicesCompanyInfoVoList(String companyName, Integer pageNo, Integer pageSize){
        PagedInput pagedInput = new PagedInput(pageSize, pageNo);
        PagedOutput<ServicesCompanyInfoModel> pagedOutput = repository.pagingList(PredicateBuilder.conjunction()
                .and(() -> Q.isDelete.eq(false))
                .ifHasTextThenAnd(companyName, () -> Q.companyName.like("%" + companyName + "%"))
                .get(), pagedInput, new OrderSpecifier<>(Order.ASC, Q.idx));
        List<ServicesCompanyInfoVo> list = new ArrayList<>();
        if(pagedOutput != null && pagedOutput.getData() != null) {
            list = pagedOutput.getData().stream().map(e -> {
                ServicesCompanyInfoVo servicesCompanyInfoVo = new ServicesCompanyInfoVo();
                baseUtils.convertEntityToDto(e, servicesCompanyInfoVo);
                servicesCompanyInfoVo.setLastUpdateTimeStr(DateUtils.getDateSecondFormat(e.getCreateTime()));
                return servicesCompanyInfoVo;
            }).collect(Collectors.toList());
            return new PagedOutput(pagedInput, pagedOutput.getTotalElements(), list);
        }
        return new PagedOutput(pagedInput, 0, list);
    }

    /**
     *
     * 功能描述: 删除物流商
     *
     * @param id 物流商id
     * @return
     * @auther: Kien
     * @date: 2019/6/12 20:37
     */
    @Transactional
    public DataOutput delExpressageCompany(Long id, HttpServletRequest request) {
        Long userId = UserSession.getUserIdBySession(request);
        if(null == userId) { // 未登录
            return new DataOutput(CommonStatus.UNAUTHORIZED);
        }
        if(null == id) { // 物流id为空
            return new DataOutput(CommonStatus.BAD_REQUEST.getCode(), "物流商id不能为空");
        }
        // 逻辑删除
        Date date = new Date();
        int i = repository.updateByWhere(PredicateBuilder.conjunction().and(() -> Q.id.eq(id)).get(), it -> {
            it.set(Q.isDelete, true);
            it.set(Q.lastUpdateBy, userId);
            it.set(Q.lastUpdateTime, date);
        });
        if(i != 0) {
            // 把对应物流商匹配字删除
            int i1 = expressageMatchingDetailCmsService.delExpressageMatchingDetailByCompanyId(id, userId, date);
        }
        return new DataOutput(CommonStatus.SUCCESS.getCode(), "删除成功");
    }
}

